package com.dongdongshop.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.pojo.TbOrder;
import com.dongdongshop.service.OrderService;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.UUID;

/**
 * 监听要发送是事务组
 */
@Controller
@RocketMQTransactionListener(txProducerGroup = "tx-group")
public class MQCallBackTransactionListener implements RocketMQLocalTransactionListener {
    @Reference(timeout = 500000)
    private OrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 消息回调
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {

        /** 消息的头信息*/
        MessageHeaders headers = message.getHeaders();
        /** x消息具体内容*/
        String s = new String((byte[]) message.getPayload());
        System.out.println(s);
        TbOrder tbOrder = (TbOrder) o;
        String id = message.getHeaders().getId().toString();

        try {
            orderService.updateByOrder(tbOrder.getOrderNum(), tbOrder.getSerialNum());
        } catch (Exception e) {
            e.printStackTrace();
            /** 失败*/
            redisTemplate.boundHashOps("mqmessage").put(id, "2");
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        /** 告诉mq 消费提交*/
        /** 成功*/
        redisTemplate.boundHashOps("mqmessage").put(id, "1");
        return RocketMQLocalTransactionState.COMMIT;
    }

    /**
     * 消息会查
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String id = message.getHeaders().getId().toString();
        String mqmessage = (String) redisTemplate.boundHashOps("mqmessage").get(id);
        /** 可以避免空指针*/
        if (Objects.equals(mqmessage, "1")) {
            return RocketMQLocalTransactionState.COMMIT;
        } else if (Objects.equals(mqmessage, "2")) {
            return RocketMQLocalTransactionState.ROLLBACK;
        } else {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
